package com.sjy.project.fym.place.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.validation.Validator;

import com.sjy.common.constant.UserConstants;
import com.sjy.common.exception.ServiceException;
import com.sjy.common.utils.DateUtils;
import com.sjy.common.utils.GPSUtil;
import com.sjy.common.utils.Point;
import com.sjy.common.utils.StringUtils;
import com.sjy.common.utils.bean.BeanValidators;
import com.sjy.common.utils.security.ShiroUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sjy.project.fym.place.mapper.FyPlaceMapper;
import com.sjy.project.fym.place.domain.FyPlace;
import com.sjy.project.fym.place.service.IFyPlaceService;
import com.sjy.project.fym.team.domain.FyTeam;
import com.sjy.project.fym.team.mapper.FyTeamMapper;
import com.sjy.project.fym.user.mapper.FyUserMapper;
import com.sjy.project.system.user.service.UserServiceImpl;
import com.sjy.common.utils.text.Convert;
import com.sjy.framework.aspectj.lang.annotation.DataScope;
import com.sjy.framework.web.domain.Ztree;

/**
 * 防疫点信息Service业务层处理
 * 
 * @author sjy
 * @date 2022-04-17
 */
@Service
public class FyPlaceServiceImpl implements IFyPlaceService 
{
	private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private FyPlaceMapper fyPlaceMapper;
    @Autowired
    private FyTeamMapper fyTeamMapper;
    @Autowired
    private FyUserMapper fyUserMapper;
    @Autowired
    protected Validator validator;
    /**
     * 查询防疫点信息
     * 
     * @param placeId 防疫点信息主键
     * @return 防疫点信息
     */
    @Override
    public FyPlace selectFyPlaceByPlaceId(Long placeId)
    {
    	FyPlace place = fyPlaceMapper.selectFyPlaceByPlaceId(placeId);
    	if(place==null) {
    		return null;
    	}
    	List<FyTeam> fyTeams = fyTeamMapper.selectFyTeamListByPlaceId(placeId);
    	fyTeams.forEach(n->{
    		n.setFyUsers(fyUserMapper.selectFyUserListByTeamId(n.getTeamId()));
    	});
    	place.setFyTeams(fyTeams);
        return place;
    }
    
    public FyPlace selectById(Long placeId) {
    	return fyPlaceMapper.selectFyPlaceByPlaceId(placeId);
    }

    /**
     * 查询防疫点信息列表
     * 
     * @param fyPlace 防疫点信息
     * @return 防疫点信息
     */
    @Override
    public List<FyPlace> selectFyPlaceList(FyPlace fyPlace)
    {
        return fyPlaceMapper.selectFyPlaceList(fyPlace);
    }
    /**
     *批量场所Ids获取placeNames
     * 
     * @param placeIds 防疫点信息主键
     * @return 防疫点信息
     */
    public String selectFyPlaceNamesByPlaceIds(String placeIds) {
    	return fyPlaceMapper.selectFyPlaceNamesByPlaceIds(placeIds);
    }
    /**
     * 新增防疫点信息
     * 
     * @param fyPlace 防疫点信息
     * @return 结果
     */
    @Override
    public int insertFyPlace(FyPlace fyPlace)
    {
        fyPlace.setCreateTime(DateUtils.getNowDate());
        return fyPlaceMapper.insertFyPlace(fyPlace);
    }

    /**
     * 修改防疫点信息
     * 
     * @param fyPlace 防疫点信息
     * @return 结果
     */
    @Override
    public int updateFyPlace(FyPlace fyPlace)
    {
        fyPlace.setUpdateTime(DateUtils.getNowDate());
        return fyPlaceMapper.updateFyPlace(fyPlace);
    }
    
    /**
     * 批量修改防疫点信息
     * 
     * @param fyPlace 防疫点信息
     * @return 结果
     */
    public int updateFyPlaceMultiple(String placeIds,String status,Integer signInRadius) {
    	return fyPlaceMapper.updateFyPlaceMultiple(placeIds, status, signInRadius);
    }

    /**
     * 通过防疫点名称查询防疫点
     * 
     * @param placeName 防疫点名称
     * @return 防疫点对象信息
     */
    public FyPlace selectPlaceByPlaceName(String placeName) {
    	return fyPlaceMapper.selectPlaceByPlaceName(placeName);
    }
    /**
     * 批量删除防疫点信息
     * 
     * @param placeIds 需要删除的防疫点信息主键
     * @return 结果
     */
    @Override
    public int deleteFyPlaceByPlaceIds(String placeIds)
    {
        return fyPlaceMapper.deleteFyPlaceByPlaceIds(Convert.toStrArray(placeIds));
    }

    /**
     * 删除防疫点信息信息
     * 
     * @param placeId 防疫点信息主键
     * @return 结果
     */
    @Override
    public int deleteFyPlaceByPlaceId(Long placeId)
    {
        return fyPlaceMapper.deleteFyPlaceByPlaceId(placeId);
    }
    /**
     * 根据用户userId查询当前他所签到的场所
     * 
     * @param userId 用户编号
     * @return 防疫点对象信息
     */
    public FyPlace selectFyPlaceBySigninUserId(Long userId) {
    	return fyPlaceMapper.selectFyPlaceBySigninUserId(userId);
    }
    /**
     * 导入用户数据
     * 
     * @param placeList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importPlace(List<FyPlace> placeList, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(placeList) || placeList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String operName = ShiroUtils.getLoginName();
        for (FyPlace place : placeList)
        {
            try
            {
                // 验证是否存在这个防疫点
                FyPlace u = fyPlaceMapper.selectPlaceByPlaceName(place.getPlaceName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, place);
                    //更新lngSjy latSjy 到 lng lat
                    double[] lnglat = GPSUtil.bd09_To_gps84(new Double(place.getLatSjy()+""), new Double(place.getLngSjy()+""));
                    place.setLng(new BigDecimal(lnglat[1]));
                    place.setLat(new BigDecimal(lnglat[0]));
                    //设计院那边实际的经纬度格式
//                    Point point = GPSUtil.gps84_To_cgs2000(lnglat[1],lnglat[0]);
//                    place.setLngSjy(point.getX());
//                    place.setLatSjy(point.getY());
                    
                    //place.setLng(new BigDecimal(place.getLnglat().split(",")[0]));
                    //place.setLat(new BigDecimal(place.getLnglat().split(",")[1]));
                    place.setStatus(place.getStatus());
                    place.setCreateBy(operName);
                    this.insertFyPlace(place);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、防疫点 " + place.getPlaceName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, place);
                  //更新lngSjy latSjy 到 lng lat
                    double[] lnglat = GPSUtil.bd09_To_gps84(new Double(place.getLatSjy()+""), new Double(place.getLngSjy()+""));
                    place.setLng(new BigDecimal(lnglat[1]));
                    place.setLat(new BigDecimal(lnglat[0]));
                    //设计院那边实际的经纬度格式
//                    double[] lnglat2 = GPSUtil.gps84_To_Gcj02(lnglat[0],lnglat[1]);
//                    place.setLngSjy(lnglat2[1]);
//                    place.setLatSjy(lnglat2[0]);
                    
                    place.setStatus(place.getStatus());
                    
                    place.setPlaceId(u.getPlaceId());
                    place.setUpdateBy(operName);
                    this.updateFyPlace(place);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、防疫点 " + place.getPlaceName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、防疫点 " + place.getPlaceName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、防疫点 " + place.getPlaceName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    

    /**
     * 查场所管理树
     * @param fyPlace 场所信息
     * @return 所有场所信息
     */
    @Override
    public List<Ztree> selectPlaceTree(FyPlace fyPlace)
    {
        List<FyPlace> placeList = fyPlaceMapper.selectFyPlaceList(fyPlace);
        List<Ztree> ztrees = initZtree(placeList);
        return ztrees;
    }
    
    /**
     * 对象转部门树
     *
     * @param placeList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<FyPlace> placeList)
    {
        return initZtree(placeList, null);
    }

    /**
     * 对象转部门树
     *
     * @param placeList 部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<FyPlace> placeList, List<String> roleDeptList)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (FyPlace fyPlace : placeList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(fyPlace.getPlaceId());
            ztree.setpId(null);
            ztree.setName(fyPlace.getPlaceName());
            ztree.setTitle(fyPlace.getAddr());
            ztree.setChkDisabled(true);
            
            if (isCheck)
            {
                ztree.setChecked(roleDeptList.contains(fyPlace.getPlaceId() + fyPlace.getPlaceName()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }

}
